package com.btr.ivle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.btr.ivle.R;
import com.btr.ivle.backgroud.AsyncTaskCompleteListener;
import com.btr.ivle.backgroud.GetEventsTask;
import com.btr.ivle.backgroud.GetModulesTask;
import com.btr.ivle.backgroud.GetNewsTask;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.DatabaseEvent;
import com.btr.ivle.helper.DatabaseModule;
import com.btr.ivle.helper.IsNetworkAvailable;

public class MainActivity extends SherlockListActivity implements ActionBar.TabListener, AsyncTaskCompleteListener<String>{
	
	private Context myApp = this;
	private GetModulesTask getModuleTask;
	private GetEventsTask getEvents;
	private GetNewsTask getNews;
	private List<Map<String, String>> list;
	private int selectedTab = TABMODULE;
	private boolean isModulesSelected = false, isEventsSelected = false, isNewsSelected = false;
	private MenuItem item;
	
	public final static String EXTRA_MESSAGE = ".MainActivity.Msg.id";
	public final static String MSG_ISEVENT = ".MainActivity.Msg.isEvent";
	
	public final static int TABMODULE = 0;
	public final static int TABEVENT = 1;
	public final static int TABNEWS = 2;
	public final static int TABMORE = 3;
	
	public void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Theme_Sherlock_Light);
		super.onCreate(savedInstanceState);
		
        final ActionBar ab = getSupportActionBar();
        ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    }
	
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	  super.onSaveInstanceState(savedInstanceState);
	  savedInstanceState.putBoolean("isModulesSelected", isModulesSelected);
	  savedInstanceState.putBoolean("isEventsSelected", isEventsSelected);
	  savedInstanceState.putBoolean("isNewsSelected", isNewsSelected);
	  savedInstanceState.putInt("selectedTab", selectedTab);
	}
	
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
	  super.onRestoreInstanceState(savedInstanceState);
	  isModulesSelected = savedInstanceState.getBoolean("isModulesSelected");
	  isEventsSelected = savedInstanceState.getBoolean("isEventsSelected");
	  isNewsSelected = savedInstanceState.getBoolean("isNewsSelected");
	  selectedTab = savedInstanceState.getInt("selectedTab");
	}
	
	private void setModuleListView(List<Map<String, String>> list){
        SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.modulelist,  
                new String[]{"CourseCode","CourseName"},  
                new int[]{R.id.CourseCode,R.id.CourseName});  
        setListAdapter(adapter);
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {
        	  Intent intent = new Intent(MainActivity.this, ListModuleItemActivity2.class);
	          intent.putExtra(EXTRA_MESSAGE, String.valueOf(position));
	          startActivity(intent);
          }
        });
	}
	private void setEventListView(final List<Map<String, String>> list){
		final DatabaseEvent dbEvent = new DatabaseEvent(this,IVLEToken.getUserID()+"_Event",null,getResources().getInteger(R.integer.DBVersion));
		SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.eventslist,  
                new String[]{dbEvent.Title},  
                new int[]{R.id.eventTitle});
        setListAdapter(adapter);
	    ListView lv = getListView();
	    lv.setTextFilterEnabled(true);
	    
	    lv.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View view,
	            int position, long id) {
	            Intent intent = new Intent(MainActivity.this, ViewEventActivity.class);
	            intent.putExtra(EXTRA_MESSAGE, list.get(position).get(dbEvent.ID));
	            intent.putExtra(MSG_ISEVENT, selectedTab==TABEVENT);
	            startActivity(intent);
	        }
	      });
	}
	
	private void getModuleFromDB(){
		DatabaseModule db = new DatabaseModule(this,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion));
        String table = IVLEToken.getUserID(); 
        String[] columns = new  String[] {db.colCode,db.colName}; 
        String selection = null;
        String[] selectionArgs = null; 
        String groupBy = null ; 
        String having = null ; 
        String orderBy = db.colCode + " ASC"; 
        String limit = null ; 
        Cursor c = db.getReadableDatabase().query(table, columns, 
        		selection, selectionArgs, groupBy, having, orderBy, limit);
        c.moveToFirst();

        Map<String, String> map;
        list = new ArrayList<Map<String, String>>();
        
        for  ( int  i =  0 ; i < c.getCount(); i++) { 
        	map = new HashMap<String, String>();
        	map.put("CourseCode", c.getString(0));
    		map.put("CourseName", c.getString(1));
    		list.add(map);
	        c.moveToNext();
        }
        c.close();
        db.getReadableDatabase().close();
        db.close();
        setModuleListView(list);
	}	
	private void getEventFromDB(String isEvent){
		DatabaseEvent dbEvent = new DatabaseEvent(this,IVLEToken.getUserID()+"_Event",null,getResources().getInteger(R.integer.DBVersion));
        String table = IVLEToken.getUserID()+"_Event"; 
        String[] columns = new  String[] {dbEvent.Title, dbEvent.ID}; 
        String selection = dbEvent.isEvent + "=?";
		String[] selectionArgs = new  String[] {isEvent};
        Cursor c = dbEvent.getReadableDatabase().query(table, columns, 
        		selection, selectionArgs, null, null, null, null);
        c.moveToFirst();

        Map<String, String> map;
        list = new ArrayList<Map<String, String>>();
        
        for  ( int  i =  0 ; i < c.getCount(); i++) {
        	map = new HashMap<String, String>();
        	map.put(dbEvent.Title, c.getString(0));
        	map.put(dbEvent.ID, c.getString(1));
    		list.add(map);
	        c.moveToNext();
        }
        c.close();
        dbEvent.getReadableDatabase().close();
        dbEvent.close();
        setEventListView(list);
	}
	
	private void addTab(String text, int position){
    	ActionBar.Tab tab = getSupportActionBar().newTab();
        tab.setText(text);
        tab.setTabListener(this);
        getSupportActionBar().addTab(tab, position, false);
    }
	
	public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.layout.menu_refresh, menu);
        item = menu.findItem(R.id.refresh);
        
        addTab("Modules", TABMODULE);
        addTab("Events", TABEVENT);
        addTab("IVLE News", TABNEWS);
        //addTab("More", TABMORE);
        
        getSupportActionBar().selectTab(getSupportActionBar().getTabAt(selectedTab));
        
        return true;
    }
	
    public boolean onOptionsItemSelected(final MenuItem item) 
    {
    	switch (item.getItemId()) {
        	case R.id.refresh:
	        	this.item = item;
	        	if(selectedTab==TABMODULE){
	    			if(!IVLEToken.isOffline()){
		    	        if(IsNetworkAvailable.check(myApp)){
		    	        	item.setActionView(R.layout.progressbarindeterminatesmall);
		    		        getModuleTask = new GetModulesTask(myApp);
		    		        getModuleTask.execute();
		    	        }else{
		    	        	Toast.makeText(myApp, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
		    	        	IVLEToken.setOffline(true);
		    	        }
		            }
	        	}
	    		if(selectedTab==TABEVENT){
	    			if(!IVLEToken.isOffline()){
		    	        if(IsNetworkAvailable.check(myApp)){
		    	        	item.setActionView(R.layout.progressbarindeterminatesmall);
		    	        	getEvents = new GetEventsTask(myApp);
		    	        	getEvents.execute();
		    	        }else{
		    	        	Toast.makeText(myApp, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
		    	        	IVLEToken.setOffline(true);
		    	        }
		            }
	    		}
	    		if(selectedTab==TABNEWS){
	    			if(!IVLEToken.isOffline()){
		    	        if(IsNetworkAvailable.check(myApp)){
		    	        	item.setActionView(R.layout.progressbarindeterminatesmall);
		    	        	getNews = new GetNewsTask(myApp);
		    	        	getNews.execute();
		    	        }else{
		    	        	Toast.makeText(myApp, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
		    	        	IVLEToken.setOffline(true);
		    	        }
		            }
	    		}
	        	break;
    	}
          return true;
    }
    
    public void onTabReselected(Tab tab, FragmentTransaction transaction) {
    }  
    public void onTabSelected(Tab tab, FragmentTransaction transaction) {
    	if(tab.getText().equals("Modules")){
    		getModuleFromDB();
    		selectedTab = TABMODULE;
    		if(!isModulesSelected){
	            if(!IVLEToken.isOffline()){
	    	        if(IsNetworkAvailable.check(myApp)){
	    	        	item.setActionView(R.layout.progressbarindeterminatesmall);
	    		        getModuleTask = new GetModulesTask(myApp);
	    		        getModuleTask.execute();
	    	        }else{
	    	        	Toast.makeText(myApp, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
	    	        	IVLEToken.setOffline(true);
	    	        }
	            }
	            isModulesSelected = true;
    		}
    	}
    	if(tab.getText().equals("Events")){
    		getEventFromDB("1");
    		selectedTab = TABEVENT;
    		if(!isEventsSelected){
	    		if(!IVLEToken.isOffline()){
	    	        if(IsNetworkAvailable.check(myApp)){
	    	        	item.setActionView(R.layout.progressbarindeterminatesmall);
	    	        	getEvents = new GetEventsTask(myApp);
	    	        	getEvents.execute();
	    	        }else{
	    	        	Toast.makeText(myApp, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
	    	        	IVLEToken.setOffline(true);
	    	        }
	            }
	    		isEventsSelected = true;
    		}
    	}
    	if(tab.getText().equals("IVLE News")){
    		getEventFromDB("0");
    		selectedTab = TABNEWS;
    		if(!isNewsSelected){
	    		if(!IVLEToken.isOffline()){
	    	        if(IsNetworkAvailable.check(myApp)){
	    	        	item.setActionView(R.layout.progressbarindeterminatesmall);
	    	        	getNews = new GetNewsTask(myApp);
	    	        	getNews.execute();
	    	        }else{
	    	        	Toast.makeText(myApp, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
	    	        	IVLEToken.setOffline(true);
	    	        }
	            }
	    		isNewsSelected = true;
    		}
    	}
    }
    public void onTabUnselected(Tab tab, FragmentTransaction transaction) {
    	if(tab.getText().equals("Modules")){
    		if(getModuleTask!=null){
    			if(getModuleTask.cancel(true))
    				isModulesSelected = false;
    		}
    	}
    	if(tab.getText().equals("Events")){
    		if(getEvents!=null)
    			if(getEvents.cancel(true))
    				isEventsSelected = false;
    	}
    	if(tab.getText().equals("IVLE News")){
    		if(getNews!=null)
    			if(getNews.cancel(true))
    				isNewsSelected = false;
    	}
    	item.setActionView(null);
    }
    
	public void onAsyncTaskComplete(String result) {
		if(selectedTab==TABMODULE)
			getModuleFromDB();
		if(selectedTab==TABEVENT)
			getEventFromDB("1");
		if(selectedTab==TABNEWS)
			getEventFromDB("0");
		if(item!=null)
			item.setActionView(null);
	}
	
    public void onDestroy(){
    	if(this.getModuleTask!=null)
    		if(getModuleTask.cancel(true))
				isModulesSelected = false;
    	if(getEvents!=null)
    		if(getEvents.cancel(true))
				isEventsSelected = false;
    	if(getNews!=null)
    		if(getNews.cancel(true))
				isNewsSelected = false;
    	super.onDestroy();
    }
}